<template>
  <div class="wrap">
    <!-- 海报-->
    <canvas canvas-id="qrcodeCanvas" height="1334" style="width: 750px;height: 1334px;position: fixed;top: -1500px;left: 0" width="750" />
    <!-- 朋友圈分享-->
    <Popup ref="pyqRef" mask>
      <div style="margin-top: -400rpx; margin-right: -100rpx" @tap.stop="pyqRefChange"><Image name="wxshare-timeline" oss size="500" type="png" /></div>
    </Popup>
    <div :style="{background: autoBG(posterBG_GL), paddingTop: '78rpx'}" class="poster" />
    <div class="card">
      <div class="avatar"><Image :name="state.personAvatar" overspread size="100" /></div>
      <div class="user_info">
        <div class="user_name">{{ state.personName }}</div>
        <div class="user_mobile">{{ state.personMobile }}</div>
      </div>
      <Image :name="inviteCodeImg" base64 size="100" />
    </div>
    <div class="share">
      <template
        v-for="d in tools"
        :key="d.image"
      >
        <div
          v-if="!d.weixinShare"
          class="share_item"
          @tap="d.func"
        >
          <div class="_image"><Icon :name="d.image" size="50" /></div>
          <div class="_label">{{ d.label }}</div>
        </div>
        <div
          v-else
          class="share_item"
        >
          <button class="share_item" open-type="share">
            <div class="_image"><Icon :name="d.image" size="50" /></div>
            <div class="_label">{{ d.label }}</div>
          </button>
        </div>
      </template>
    </div>
    <div class="data_tracking" @tap="goDataTracking">
      <Icon name="icon-erweimashujuzhuizong" size="30" />
      <div style="flex: 1 1; padding-left: 20rpx">数据追踪</div>
      <Icon :styles="{opacity: 0.45}" name="icon-youjiantou" size="40" />
    </div>
  </div>
</template>

<script lang="ts" setup>
import { autoBG, obj_oto_query, onLoad, onShareAppMessage, onShareTimeline, Router, storeState } from '@U/common'
import { computed, ref } from 'vue'
import { MsgLoading, Msg, PMsgLoadingClean } from '@C/Msg'
import Icon from '@C/Icon.vue'
import Image from '@C/Image.vue'
import Popup from '@C/Popup.vue'
import setCV from '@U/setCV'
import sendNote from '@U/sendNote'
import { getWeiXinInviteLink } from './request'
import type { IObj } from '@/interface'

onLoad(() => {
  // 分享给朋友
  onShareAppMessage(() => ({
    path: `/pages/Login/Login?${obj_oto_query(shareState.value)}`,
    ...shareParams.value,
  }))
  // 分享到朋友圈
  onShareTimeline(() => ({
    query: `${obj_oto_query(shareState.value)}`,
    ...shareParams.value,
  }))
})
const ctx = uni.createCanvasContext('qrcodeCanvas')

// 去数据追踪
const goDataTracking = () => Router.push('dataTracking')

// poster背景图
const posterBG_GL = `${import.meta.env.VITE_SHOUDAO_OSS_URL}/gl_qrcode_poster.png`
const zhiKePoster = `${import.meta.env.VITE_SHOUDAO_OSS_URL}/zhike_poster.png`
// 邀请码图片
const inviteCode = computed(() => storeState.inviteCode)
const inviteCodeImg = computed(() => storeState.inviteCodeImg)

// 朋友圈分享图
const pyqRef = ref()
const pyqRefChange = () => pyqRef.value.change()

const getLink = async (state: number) => {
  await MsgLoading()
  const res = await getWeiXinInviteLink({
    path: '/pages/Login/Login',
    query: obj_oto_query({
      inviteCode: shareState.value.inviteCode,
      RegWay: state,
    }),
  }).finally(() => {})
  if (res?.code === 200) {
    PMsgLoadingClean()
    if (state === 4) sendNote(`${storeState.zhiKeInfo?.name}邀请您成为${storeState.accountFirm}合伙人，点击链接立即加入\n${res.data}`)
    if (state === 5) setCV(`${storeState.zhiKeInfo?.name}邀请您成为${storeState.accountFirm}合伙人，点击链接立即加入\n${res.data}`, '链接已复制到剪切板')
  }
}

// 功能栏
const tools = [
  {
    label: '下载海报',
    image: 'icon-xingzhuang',
    func: () => {
      // 判断是否授权
      uni.authorize({
        scope: 'scope.writePhotosAlbum',
        success() {
          drawCanvas()
        },
        complete() {
          uni.getSetting({
            success(setRes) {
              if (!setRes.authSetting['scope.writePhotosAlbum']) {
                Msg({ icon: 'error', msg: '请在设置中授权：添加到相册' })
              }
            },
          })
        },
      })
    },
  },
  { label: '微信邀请', image: 'icon-weixin', func: () => {}, weixinShare: true },
  { label: '朋友圈邀请', image: 'icon-pengyouquan', func: () => { pyqRefChange() } },
  {
    label: '短信邀请',
    image: 'icon-duanxinyaoqing',
    func: () => getLink(4),
  },
  {
    label: '链接邀请',
    image: 'icon-lianjieyaoqing',
    func: () => getLink(5),
  },
]

// 状态
const state = computed(() => ({
  personName: storeState.zhiKeInfo.name,
  personMobile: storeState.zhiKeInfo.mobile,
  personAvatar: storeState.userAvatar,
}))
// 分享参数
const shareState = computed(() => ({
  inviteCode: inviteCode.value, // 注册码
  RegWay: 2, // 微信邀请
}))

// 分享参数
const shareParams = computed(() => ({
  title: `${state.value.personName}给您发送了合作邀请`,
  imageUrl: `${import.meta.env.VITE_SHOUDAO_OSS_URL}/qrcode_ct_hhr1.png`,
}))

// 绘制海报并保存到系统相册
function drawCanvas() {
  MsgLoading('生成中')
  // 背景图
  uni.downloadFile({
    url: zhiKePoster,
    success(bgRes: IObj) {
      uni.getImageInfo({
        src: bgRes.tempFilePath,
        success(res) {
          // 设置画布大小
          ctx.setFillStyle('#FFFFFF')
          ctx.fillRect(0, 0, 750, 1334)
          // 设置背景图
          ctx.drawImage(res.path, 0, 0, 750, 1334)
          // eslint-disable-next-line @typescript-eslint/ban-ts-comment
          // @ts-ignore
          const fsm = wx.getFileSystemManager()
          // eslint-disable-next-line @typescript-eslint/ban-ts-comment
          // @ts-ignore
          const filePath = `${wx.env.USER_DATA_PATH}/tmp_base64src`
          fsm.writeFile({
            filePath,
            data: inviteCodeImg.value,
            encoding: 'base64',
            success() {
              // 邀请二维码
              ctx.setFillStyle('#d3b3a7')
              ctx.fillRect(490, 1080, 200, 200)
              ctx.beginPath()
              ctx.arc(590, 1180, 100, 0, Math.PI * 2, false)
              ctx.clip()
              ctx.drawImage(filePath, 490, 1080, 200, 200)
              ctx.restore()
              drawFn()
            },
            fail() { PMsgLoadingClean({ icon: 'error', msg: '生成失败:码' }) },
          })
        },
        fail() { PMsgLoadingClean({ icon: 'error', msg: '生成失败:头像g' }) },
      })
    },
    fail() { PMsgLoadingClean({ icon: 'error', msg: '生成失败:背景' }) },
  })
}
// 绘制并保存
function drawFn() {
  // 生成图片保存
  ctx.draw(false, () => {
    uni.canvasToTempFilePath({
      canvasId: 'qrcodeCanvas',
      success(toImageRes: IObj) {
        uni.saveImageToPhotosAlbum({
          filePath: toImageRes.tempFilePath,
          success() { PMsgLoadingClean({ icon: 'success', msg: '已保存至相册' }) },
          fail() { PMsgLoadingClean({ icon: 'error', msg: '海报保存失败' }) },
        })
      },
      fail() { PMsgLoadingClean({ icon: 'error', msg: '生成失败:转换' }) },
    })
  })
}
</script>

<style lang="less" scoped>
.wrap {
  padding: 22rpx 22rpx 130rpx;
  .poster {
    height: 576rpx;
    color: white;
    text-align: center;
    .firm_name {
      width: 600rpx;
      font-size: 44rpx;
      line-height: 60rpx;
      margin: 0 auto;
    }
    .tips {
      font-size: 72rpx;
      line-height: 100rpx;
    }
  }
  .card {
    background: white;
    height: 130rpx;
    padding: 0 42rpx 0 28rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .avatar {
      width: 100rpx;
      height: 100rpx;
      border-radius: 50%;
      overflow: hidden;
    }
    .user_info {
      flex: 1 1;
      height: 100%;
      padding: 26rpx 22rpx;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      .user_name {
        font-size: 28rpx;
        color: rgba(0, 0, 0, 0.85);
      }
      .user_mobile {
        font-size: 24rpx;
        color: rgba(0, 0, 0, 0.65);
      }
    }
  }
  .share {
    height: 210rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 28rpx 0;
    .share_item {
      height: 100%;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      align-items: center;
      ._image {
        height: 108rpx;
        width: 108rpx;
        flex: 0 0 108rpx;
        background: white;
        border-radius: 20rpx;
        display: flex;
        justify-content: center;
        align-items: center;
        margin-bottom: 6rpx;
      }
      ._label {
        font-size: 24rpx;
        color: #464646;
        line-height: 30rpx;
      }
    }
  }
  .data_trace {
    background: white;
    height: 88rpx;
    margin-bottom: 28rpx;
    display: flex;
    align-items: center;
    padding: 0 32rpx 0 52rpx;
    ._label {
      flex: 1 1;
      margin-left: 18rpx;
      font-size: 28rpx;
      color: #464646;
    }
  }
}

.data_tracking {
  background: white;
  border-radius: 10rpx;
  height: 80rpx;
  display: flex;
  align-items: center;
  padding: 0 20rpx;
}
</style>
